package com.ggy.babybed.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ggy.babybed.R;
import com.ggy.babybed.fragment.AboutFragment;
import com.ggy.babybed.fragment.BabyInfoFragment;
import com.ggy.babybed.fragment.MainFragment;
import com.ggy.babybed.fragment.SelfInfoFragment;
import com.ggy.babybed.fragment.SwayFragment;
import com.ggy.babybed.model.BaseModel;
import com.ggy.babybed.model.IModel;
import com.ggy.babybed.service.ObserveNodeService;
import com.ggy.babybed.service.ObserveNodeService.ServiceBinder;
import com.ggy.babybed.service.ObserveNodeServiceImpl;
import com.yalantis.phoenix.PullToRefreshView;

import org.apache.commons.lang3.StringUtils;


/**
 * Created by ggy on 2016/7/8.
 */
public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,
        SharedPreferences.OnSharedPreferenceChangeListener,
        SwayFragment.OnFragmentInteractionListener,
        SelfInfoFragment.OnFragmentInteractionListener,
        BabyInfoFragment.OnFragmentInteractionListener,
        MainFragment.OnFragmentInteractionListener,
        AboutFragment.OnFragmentInteractionListener{

    public static final String TAG = "MainActivity";

    private FragmentManager mManager;
    private FragmentTransaction mTransaction;
    private IModel mModel;

    private ObserveNodeService mMessageService;
    private ServiceBinder mObserverService;

    private MainFragment mMainFragment;
    private PullToRefreshView mPullToRefreshView;
    private static final long REFRESH_DELAY = 1000;
    private float percentage = 0f;

    private ImageView header_image;
    private TextView h_name;
    private TextView h_sign;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        isLogin();

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        initModel();

        mPullToRefreshView = (PullToRefreshView)findViewById(R.id.pull_to_refresh);
        mPullToRefreshView.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPullToRefreshView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mPullToRefreshView.setRefreshing(false);
                        refreshData();
                        Log.i(TAG, "refresh successed...");
                    }
                }, REFRESH_DELAY);
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        navigationView.setBackgroundColor(getResources().getColor(R.color.menu_color));
        navigationView.setItemTextColor(ColorStateList.valueOf(getResources().getColor(android.R.color.white)));
        View headView = navigationView.inflateHeaderView(R.layout.nav_header_main);
        initHeadView(headView);
        MyApplication.getPreferences().registerOnSharedPreferenceChangeListener(this);

        mManager = getSupportFragmentManager();
        setDefaultFragment();
        Intent intent= new Intent(this,ObserveNodeServiceImpl.class);
        bindService(intent,connection,Context.BIND_AUTO_CREATE);
    }

    private void initHeadView(View headView){
        header_image = (ImageView) headView.findViewById(R.id.header_image);
        String path = MyApplication.getValue(getString(R.string.si_head_icon));
        if(StringUtils.isNotBlank(path)){
            header_image.setImageBitmap(BitmapFactory.decodeFile(path));
        }else{
            header_image.setImageDrawable(getResources().getDrawable(R.drawable.head));
        }
        h_name = (TextView) headView.findViewById(R.id.header_name);
        h_name.setText(MyApplication.getValue(getString(R.string.si_name)));
        h_sign = (TextView) headView.findViewById(R.id.header_sign);
        h_sign.setText(MyApplication.getValue(getString(R.string.si_sign)));
    }

    private void isLogin(){
        String login_name = MyApplication.getValue("login_name");
        String login_pass = MyApplication.getValue("login_pass");

        if(StringUtils.isAnyBlank(login_name, login_pass)){
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
        }
    }

    private void refreshData(){
        //TODO 获取服务器数据，更新图表
        percentage = 0.56f; //实际从服务器获取
        mMainFragment.refreshData(percentage);
    }

    private void initModel(){
        mModel = new BaseModel();
        SharedPreferences shared = getSharedPreferences("babydata", MODE_PRIVATE);
        if(null != shared){
            mModel.setID(shared.getLong("ID", 1));
            mModel.setName(shared.getString("name", "baby"));
            mModel.setPassword(shared.getString("password", "***"));
        }
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    //  getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.nav_home) {
            setDefaultFragment();
            mMainFragment.getView().refreshDrawableState();
        } else if (id == R.id.nav_baby_info) {
            Fragment fragment = BabyInfoFragment.newInstance(null, null);
            mTransaction = mManager.beginTransaction();
            mTransaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left);
            mTransaction.replace(R.id.id_content, fragment, "babyinfo").addToBackStack("babyinfo").commit();
        } else if (id == R.id.nav_person_info) {
            Fragment fragment = SelfInfoFragment.newInstance(null, null);
            mTransaction = mManager.beginTransaction();
            mTransaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left);
            mTransaction.replace(R.id.id_content, fragment, "selfinfo").addToBackStack("selfinfo").commit();
        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.about_us) {
            Fragment fragment = AboutFragment.newInstance(null, null);
            mTransaction = mManager.beginTransaction();
            mTransaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left);
            mTransaction.replace(R.id.id_content, fragment, "about").addToBackStack("about").commit();
        } else if (id == R.id.login_out) {
            MyApplication.setValue(getString(R.string.login_name), "");
            MyApplication.setValue(getString(R.string.login_email), "");
            MyApplication.setValue(getString(R.string.login_pass), "");
            isLogin();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public void setDefaultFragment(){
        if(mMainFragment==null){
            mMainFragment=new MainFragment();
        }
        mTransaction = mManager.beginTransaction();
        mManager.popBackStackImmediate();
        mTransaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left);
        mTransaction.replace(R.id.id_content, mMainFragment, "mainFragment").commit();
    }

    private ServiceConnection connection =new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mObserverService=(ServiceBinder)service;
            mMessageService=((ServiceBinder)service).getService();
            mObserverService.startAll();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mMessageService=null;
        }
    };

    @Override
    public void onFragmentInteraction(Uri uri) {
        //TODO
    }

    public void messageClick(View view) {
        Intent intent = new Intent(this, MessageActivity.class);
        startActivity(intent);
    }

    public void lookClick(View view) {
        Intent intent = new Intent(this, PlayerActivity.class);
        intent.putExtra("url", "url");
        intent.putExtra("videoname", "name");
        startActivity(intent);
    }

    public void songClick(View view) {}

    public void swayClick(View view) {
        Fragment fragment = SwayFragment.newInstance(mModel);
        mTransaction = mManager.beginTransaction();
        mTransaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left);
        mTransaction.replace(R.id.id_content, fragment, "swayFragment").addToBackStack("swayFragment").commit();
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if(StringUtils.equals(key, getString(R.string.si_head_icon))){
            String path = MyApplication.getValue(getString(R.string.si_head_icon));
            if(StringUtils.isNotBlank(path)){
                header_image.setImageBitmap(BitmapFactory.decodeFile(path));
            }else{
                header_image.setImageDrawable(getResources().getDrawable(R.drawable.head));
            }
        }
        if(StringUtils.equals(key, getString(R.string.si_name))){
            h_name.setText(MyApplication.getValue(getString(R.string.si_name)));
        }
        if(StringUtils.equals(key, getString(R.string.si_sign))){
            h_sign.setText(MyApplication.getValue(getString(R.string.si_sign)));
        }
    }

    @Override
    protected void onDestroy() {
        Log.i(TAG,"on destory!");
        unbindService(connection);
        MyApplication.getPreferences().registerOnSharedPreferenceChangeListener(this);
        super.onDestroy();
    }

}
